package category

import (
	"gitee.com/mootok/mootok/src/constant/strings"
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/storage/database"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gitee.com/mootok/mootok/src/web/api"
	"gitee.com/mootok/mootok/src/web/common/response"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
)

func (i *ApiCategoryImpl) ListCategories(c *gin.Context, params api.ListCategoriesParams) {
	var err error
	var categories []models.Category
	var cond models.Category

	logger := logging.LogService("Category.List")

	if params.Filter != nil && *params.Filter == "actual" {
		cond.IsVirtual = false
	} else {
		cond.IsVirtual = true
	}
	if err = database.Client.Find(&categories, cond).Error; err != nil {
		logger.WithFields(logrus.Fields{
			"virtual": cond.IsVirtual,
		}).Errorf("Error querying from db:%v", err)
		response.FailWithMsg(c, http.StatusInternalServerError,
			strings.DataBaseSelectErrorCode, strings.InternalServiceError)
		return
	}
	resp := make([]api.CategoryInfo, len(categories))

	for i := 0; i < len(resp); i++ {
		resp[i].Id = &categories[i].ID
		resp[i].Virtual = &categories[i].IsVirtual
		resp[i].Name = &categories[i].Name
	}

	response.SuccessWithDetail(c, strings.SuccessCode, strings.Success, &resp)
	logger.Errorf("success")
}
